package com.platform.manager.action.system;

import com.platform.common.mybatis.Page;
import com.platform.common.mybatis.context.ContextHolder;
import com.platform.domain.TbSysUser;
import com.platform.domain.TbSysUserAuthorization;
import com.platform.domain.query.TbSysUserQuery;
import com.platform.domain.result.DataGirdData;
import com.platform.domain.result.ResultData;
import com.platform.manager.action.BaseAction;
import com.platform.service.UserService;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-9-7
 * Time: 下午4:13
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/system")
@Service("userAction")
@ParentPackage("json-default")
public class UserAction extends BaseAction {

    @Resource
    private UserService userService;


    private TbSysUserQuery userQuery;

    private DataGirdData data;


    private TbSysUser user;

    /**
     * 查询用户信息列表
     *
     * @return
     */
    @Action(value = "queryUsers", results = {@Result(name = "success", type = "json", params = {"root", "data"})})
    public String queryUsers() {
        try {
            if (userQuery != null) {
                logger.info(userQuery.getName() + " | " + userQuery.getLoginId()
                        + " | " + userQuery.getDeptId() + " | " + userQuery.getJob()
                        + " | " + userQuery.getEmail() + " | " + userQuery.getMobile()
                        + " | " + userQuery.getEnabled());
            }
            // 查询符合条件的记录总数
            int totalResult = userService.queryUserInfosCount(userQuery);
            Page page = getPage();
            page.setTotalResult(totalResult);
            ContextHolder.setPage(page);
            // 查询符合条件的用户列表
            List<TbSysUser> list = userService.queryUserInfos(userQuery);
            data = new DataGirdData();
            data.setRows(list);
            data.setTotal(totalResult);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户信息
     *
     * @return
     */
    @Action(value = "queryUserInfo", results = {@Result(name = "success", location = "/system/user/user_display.jsp")})
    public String queryUserInfo() {
        try {
            logger.info("查询用户信息，用户ID：[" + userQuery.getUserId() + "]");
            List<TbSysUser> users = userService.queryUserInfos(userQuery);
            if (users != null && users.size() == 1) {
                user = users.get(0);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户信息
     *
     * @return
     */
    @Action(value = "queryUser", results = {@Result(name = "success", location = "/system/user/user_edit.jsp")})
    public String queryUser() {
        try {
            logger.info("查询用户信息，用户ID：[" + userQuery.getUserId() + "]");
            List<TbSysUser> users = userService.queryUserInfos(userQuery);
            if (users != null && users.size() == 1) {
                user = users.get(0);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户信息列表
     *
     * @return
     */
    @Action(value = "insertUser", results = {@Result(name = "success", type = "json",
            params = {"root", "result", "contentType", "text/html"})})
    public String insertUser() {
        try {
            int intResult = userService.insertUser(user);
            result = new ResultData();
            if (intResult == 1) {
                result.setSuccess(true);
                result.setMessage("保存成功！");
            } else {
                result.setSuccess(false);
                result.setMessage("保存失败！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户信息列表
     *
     * @return
     */
    @Action(value = "updateUser", results = {@Result(name = "success", type = "json",
            params = {"root", "result", "contentType", "text/html"})})
    public String updateUser() {
        try {
            int intResult = userService.updateUser(user);
            result = new ResultData();
            if (intResult == 1) {
                result.setSuccess(true);
                result.setMessage("修改成功！");
            } else {
                result.setSuccess(false);
                result.setMessage("修改失败！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 批量删除用户
     *
     * @return
     */
    @Action(value = "deleteUser", results = {@Result(name = "success", type = "json",
            params = {"root", "result", "contentType", "text/html"})})
    public String deleteUser() {
        try {
            String userIds = user.getUserId();
            String loginIds = user.getLoginId();
            logger.info(userIds);
            // 根据分隔符进行分隔成用户列表
            String[] userIdArray = userIds.split(":");
            String[] loginIdArray = userIds.split(":");
            logger.info(userIdArray.length);
            // 保存未删除成功的的用户登录名
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < userIdArray.length; i++) {
                // 删除用户
                int intResult = userService.deleteUser(userIdArray[i]);
                // 如果未成功，则将用信息加入到提示信息中
                if (intResult != 1) {
                    buffer.append(" [").append(loginIdArray[i]).append("]");
                }
            }
            result = new ResultData();
            if (buffer.length() == 0) {
                result.setSuccess(true);
                result.setMessage("删除成功！");
            } else {
                result.setSuccess(false);
                result.setMessage("删除失败！\n以下用户删除失败！\n[登录名]：" + buffer.toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户信息列表
     *
     * @return
     */
    @Action(value = "saveUserRoles", results = {@Result(name = "success", type = "json",
            params = {"root", "result", "contentType", "text/html"})})
    public String saveUserRoles() {
        try {
            String userId = user.getUserId();
            String roleIds = user.getRoleId();
            logger.info(userId + ' ' + roleIds );
            String[] roleIdArray = roleIds.split(":");
            List<TbSysUserAuthorization> list = new ArrayList<TbSysUserAuthorization>();
            for (String roleId : roleIdArray) {
                TbSysUserAuthorization userAuth = new TbSysUserAuthorization();
                userAuth.setUserId(userId);
                userAuth.setRoleId(roleId);
                list.add(userAuth);
            }
            int intResult = 0;
            if (list.size() > 0) {
                intResult =userService.saveUserRoles(list);
            }
            result = new ResultData();
            if (intResult > 0) {
                result.setSuccess(true);
                result.setMessage("修改成功！");
            } else {
                result.setSuccess(false);
                result.setMessage("修改失败！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    @JSON
    public DataGirdData getData() {
        return data;
    }

    public void setData(DataGirdData data) {
        this.data = data;
    }

    @JSON
    public TbSysUser getUser() {
        return user;
    }

    public void setUser(TbSysUser user) {
        this.user = user;
    }

    public TbSysUserQuery getUserQuery() {
        return userQuery;
    }

    public void setUserQuery(TbSysUserQuery userQuery) {
        this.userQuery = userQuery;
    }

}
